
use yew::prelude::*;
use yew_router::prelude::Router;
use yew::services::fetch::FetchTask;

use crate::view::{login::LoginView, home::HomeView, user::list::UserListView};
use crate::router::WebRouter;
use crate::utils::state::{set_api, get_api};
use crate::AppConfig;
use crate::service::app::AppService;
use crate::error::Error;

pub enum AppAction {
    LoadApi(Result<AppConfig, Error>)
}

pub struct App {
    task: Option<FetchTask>,
    load_api: Callback<Result<AppConfig, Error>>,
    service: crate::service::app::AppService
}

impl Component for App {
    type Message = AppAction;
    type Properties = ();

    fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
        let mut me = Self {
            task: None,
            load_api: link.callback(AppAction::LoadApi),
            service: AppService::new()
        };

        if get_api().is_none() {
            me.task = Some(me.service.load_api(me.load_api.clone()));
        }

        me
    }

    fn update(&mut self, msg: Self::Message) -> bool {
        match msg {
            AppAction::LoadApi(res) => {
                if let Ok(rlt) = res {
                    set_api(rlt.api);
                }
                self.task = None
            }
        }
        false
    }

    fn change(&mut self, _props: Self::Properties) -> bool {
        false
    }

    fn view(&self) -> Html {
        let s = Router::render(|r: WebRouter| match r {
            WebRouter::Login => html! { <LoginView /> },
            WebRouter::User => html! { <UserListView /> },
            WebRouter::Home => html! { <HomeView /> }
        });
        html! { <Router<WebRouter, ()> render=s /> }
    }
}
